<?php

namespace App\Http\Controllers\App;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Order;

class OrderController extends Controller
{
    /**
     * 订单展示
     *
     * @return void
     */
    public function show( Request $request )
    {
        $tel        = $request->input('tel');
        $order_sn   = $request->input('order_sn');
        $start_time = $request->input('start_time');
        $end_time   = $request->input('end_time');
        $status     = $request->input('status', null);
      
        $where     = [];
        $shop_info = session('shopInfo');

        $query = Order::orderBy('id', 'desc')->where('shop_id', '=', $shop_info['id']);
        if ( $tel ) {
            $where[] = ['user_mobile', 'like', '%'. $tel. '%'];
        }

        if ( $order_sn ) {
            $query->where('order_sn', 'like', '%'. $order_sn. '%');
           
        }
       
        if ( $start_time ) {

            $query->whereDate('created_at', '>=', $start_time);

        }
       
        if ( $end_time ) {

            $query->whereDate('created_at', '<=', $end_time);

        }
      
        if ( $status !== null ) {
              switch ($status) {
                case 0:
                    $type = 0;
                    break;

                case 1:
                    $type = 1;
                    break;

                case 2:
                    $type = 2;
                    break;
                 case 3:
                    $type = 3;
                    break;
                default:
                    return self::error('请传递正确的状态');
                    break;
            }

            $query->where('status', $type);
        }
        
        $data = $query->with([
            'user' => function ( $query ) {
                $query->select('user_mobile', 'id');
            }
        ])->whereHas('user', function ( $query ) use ( $where ) {
            $query->where($where);
        })->paginate(15);    
        
        return self::json($data);
    }

    /**
     * 提货
     *
     * @param Request $request
     * @return void
     */
    public function edit( Request $request )
    {
        $id         = $request->input('id');
        $code       = $request->input('code');
        $shop_info  = session('shopInfo');
        $shop_id    = $shop_info['id'];
        // $shop_id = 1;
      
        $info = Order::where('status', 2)->where('shop_id', $shop_id)->where('code',$code)->find($id);

        if ( !$info ) {
            return self::error('请传递正确的订单');
        }
        
        $info->status = 3;
        $info->save();

        if ( $info['is_rebate'] == 1 ) {
            Order::create_rebate_order( $info ,$shop_id);
        }

        return self::success('提货成功');
    }


}
